﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Payton.WP7.Common;
using Payton.WP7.Common.Configration;
using Payton.WP7.Common.Event;
using Payton.WP7.Common.Interface;
using Payton.WP7.Common.Model;
using Payton.WP7.Infrastructure;

namespace Payton.WP7.ViewModel
{
    public class SettingViewModel : ViewModelBase<ApplicationSetting>
    {
        private IEventAggregator _ev;

        private List<int> intervals = new List<int>() { 1, 5, 10, 30 };

        public List<int> Intervals
        {
            get { return intervals; }
            set
            {
                intervals = value;
                RaisePropertyChanged(() => Intervals);
            }
        }

        private List<int> pageCounts = new List<int>() { 10, 20, 30 };

        public List<int> PageCounts
        {
            get { return pageCounts; }
            set
            {
                pageCounts = value;
                RaisePropertyChanged(() => PageCounts);
            }
        }
        public List<string> ImageQualityTexts
        {
            get
            {
                return new List<string>() { AppResx.ImageQualityNoPixText, AppResx.ImageQualityThumbText, AppResx.ImageQualityFullText, };
            }
        }

        [XmlIgnore]
        [IgnoreDataMember]
        public static List<CultureInfo> SupportedLanguages
        {
            get
            {
                return new List<CultureInfo>() 
                { 
                    new CultureInfo("en-US"), 
                    new CultureInfo("zh-CN"), 
                };
            }
        }

        [XmlIgnore]
        [IgnoreDataMember]
        public CultureInfo Language
        {
            get
            {
                return new CultureInfo(Item.LanguageName);
            }
            set
            {
                if (value.Name != Item.LanguageName)
                {
                    Item.LanguageName = value.Name;
                    RaisePropertyChanged(() => Language);
                }
            }
        }

        [XmlIgnore]
        [IgnoreDataMember]
        public static List<KeyValuePair<string, string>> SupportedThemes
        {
            get
            {
                return new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("/Payton.WP7;component/Theme/ClassicWood.xaml", AppResx.ThemeClassicWoodText),
                    new KeyValuePair<string, string>("/Payton.WP7;component/Theme/SimpleFast.xaml", AppResx.ThemeSimpleFastText),
                };
            }
        }

        [XmlIgnore]
        [IgnoreDataMember]
        KeyValuePair<string, string> _themeItem;
        public KeyValuePair<string, string> ThemeItem
        {
            get
            {
                var item = SupportedThemes.First(i => i.Key == Item.ThemeResourceDictionaryPath);

                return item;
            }
            set
            {
                if (_themeItem.Key != value.Key)
                {
                    _themeItem = value;
                    Item.ThemeResourceDictionaryPath = value.Key;
                    RaisePropertyChanged(() => ThemeItem);
                }
            }
        }

        private ObservableCollection<ImageResolution> imageResolutions = new ObservableCollection<ImageResolution>();

        public ObservableCollection<ImageResolution> ImageResolutions
        {
            get { return imageResolutions; }
            set { imageResolutions = value; RaisePropertyChanged(() => ImageResolutions); }
        }

        private ObservableCollection<SNSAccount> bindedAccounts;

        public ObservableCollection<SNSAccount> BindedAccounts
        {
            get { return bindedAccounts; }
            set
            {
                bindedAccounts = value;
                RaisePropertyChanged(() => BindedAccounts);
            }
        }

        public ObservableCollection<SNSProvider> SupportedProviders
        {
            get
            {
                var providers = SNSProviderManager.Current.GetAllSupportedProviders().ToObservableCollection();
                return providers;
            }
        }

        private SNSProvider selectedProvider;
        public SNSProvider SelectedProvider
        {
            get
            {
                return selectedProvider;
            }
            set
            {
                selectedProvider = value;
                RaisePropertyChanged(() => SelectedProvider);
            }
        }

        protected override void Initialize()
        {
            //base.Initialize();
            BindedAccounts = AccountManager.Current.GetAllAccount().Where((a) => { return a.IsBind == true; }).ToObservableCollection();

            ImageResolutions.Add(new ImageResolution(640, 480, 50));
            ImageResolutions.Add(new ImageResolution(640, 480, 80));
            ImageResolutions.Add(new ImageResolution(480, 640, 50));
            ImageResolutions.Add(new ImageResolution(480, 640, 80));
        }

        protected override void LoadData()
        {
            Item = PhoneApplicationController.Current.AppSetting;
        }

        public void ResetSetting()
        {
            Item = PhoneApplicationController.Current.AppSetting = ApplicationSetting.Default;
        }

        public DelegateCommand Authorize { get; set; }

        public SettingViewModel()
        {
            _ev = PhoneApplicationController.Current.Container.Resolve<IEventAggregator>();
            Authorize = new DelegateCommand(AuthorizeMethod, () => { return !Loading; });
            Initialize();
            LoadData();

            if (string.IsNullOrWhiteSpace(Item.LanguageName))
            {
                Language = SupportedLanguages
                    .Any(i => Thread.CurrentThread.CurrentUICulture.Equals(i))
                    ? Thread.CurrentThread.CurrentUICulture : SupportedLanguages[0];
            }

            if (string.IsNullOrWhiteSpace(Item.ThemeResourceDictionaryPath))
            {
                ThemeItem = SupportedThemes[0];
            }

            //if (Item != null)
            //{
            //    Item.PropertyChanged += (s, e)
            //        =>
            //        {
            //            if (e.PropertyName == "ImageQuality")
            //            {
            //                RaisePropertyChanged(() => ImageQualityTexts);
            //            }
            //        };
            //}

            PropertyChanged += (o, e) =>
            {
                if (e.PropertyName == "Loading")
                {
                    Authorize.RaiseCanExecuteChanged();
                }
            };

            Item.PropertyChanged += (o, e) =>
            {
                //if (e.PropertyName == "LanguageName")
                //{
                //    PhoneApplicationController.ApplyLanguageSetting();
                //    RaisePropertyChanged("SupportedThemes");
                //}

                //if (e.PropertyName == "ThemeResourceDictionaryPath")
                //{
                //    PhoneApplicationController.ApplyTheme();
                //}
            };
        }

        private void AuthorizeMethod()
        {
            Loading = true;
            Authorize.RaiseCanExecuteChanged();
            //SNSAccount account = AccountManager.Current.GetAllAccount().Where(a => a.ServiceProvider == SelectedProvider.Type).FirstOrDefault();
            SNSProviderType t;
            if (SelectedProvider == null || SelectedProvider.Type == SNSProviderType.Unknow)
            {
                t = SNSProviderType.Sina;
            }
            else
            {
                t = SelectedProvider.Type;
            }

            AuthorizeHelper.NewRequestToken(t, (account, result) =>
            {
                ExecuteOnUIThread(() =>
                {
                    if (!result.IsSuccess)
                        MessageBox.Show(result.Message);
                    else
                    {
                        Loading = false;
                        PhoneApplicationController.Current.Container.Resolve<IEventAggregator>().GetEvent<NavigationRequestEvent>().Publish(new NavigationContext() { Destination = new Uri("/Views/AuthPage.xaml", UriKind.RelativeOrAbsolute), SimpleParameter = account.AccountID });
                    }
                });
            });
        }

        internal void DeleteAccount()
        {
            if (MessageBox.Show(AppResx.WarnDeleteSelectedAccountText, AppResx.WarnText, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                foreach (var account in AccountManager.Current.GetAllAccount().Where((a) => { return a.IsDelete == true; }))
                {
                    AccountManager.Current.RemoveAccount(account);
                }
                AccountManager.Current.Save();
            }

            BindedAccounts = AccountManager.Current.GetAllAccount().Where((a) => { return a.IsBind == true; }).ToObservableCollection();
            //throw new NotImplementedException();
        }
    }
}
